﻿using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    [RequireComponent(typeof(CButton))]
    public class UIDrag : MonoBehaviour
    {
        public bool xEnable = true;
        public bool yEnable = true;

        public RectTransform rectTransform { get { return transform as RectTransform; } }

        private Vector2 prePos;
        private Canvas canvas;
        private CButton btn;
        private bool canDrag;

        private void Start()
        {
            btn = GetComponent<CButton>();
            btn.SetPress(() =>
            {
                canDrag = true;
            });
            btn.SetRelease(() =>
            {
                canDrag = false;
            });

            canvas = transform.GetComponentInParent<CanvasScaler>().GetComponent<Canvas>();
            prePos = ScreenHelper.ScreenToUGUIPoint(Input.mousePosition, canvas);
        }

        private void Update()
        {
            if (canDrag)
            {
                Vector2 touchPos = ScreenHelper.ScreenToUGUIPoint(Input.mousePosition, canvas);
                Vector2 delta = touchPos - prePos;
                prePos = touchPos;
                Vector2 pos = rectTransform.anchoredPosition;
                if (xEnable)
                {
                    pos.x += delta.x;
                }
                if (yEnable)
                {
                    pos.y += delta.y;
                }
                rectTransform.anchoredPosition = pos;
            }
        }

    }
}
